<?php
namespace Wanecho\Mobilelogin\Api\Middlewares;

use Flarum\Foundation\ErrorHandling\JsonApiFormatter;
use Flarum\Foundation\ErrorHandling\Registry;
use Wanecho\Mobilelogin\Api\Validators\MobileValidator;
use Flarum\Foundation\ValidationException;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class RegisterMiddleware implements MiddlewareInterface
{
    /**
     * Process an incoming server request and return a response, optionally delegating
     * response creation to a handler.
     *
     * @param Request                 $request
     * @param RequestHandlerInterface $handler
     *
     * @return Response
     */
    public function process(Request $request, RequestHandlerInterface $handler): Response
    {
        
        if ($request->getUri()->getPath() === '/register') {
            $validator = resolve(MobileValidator::class);
            try {
                $validator->assertValid($request->getParsedBody());

            } catch (\Throwable $exception) {
                return (new JsonApiFormatter())->format(    
                        resolve(Registry::class)->handle($exception), 
                        $request
                );
            }
            return (new JsonApiFormatter())
                    ->format(
                        resolve(Registry::class)
                            ->handle(new ValidationException([
                                'username' => 34343,
                            ])),
                        $request
                    );

        }

        return $handler->handle($request);
    }
}